package meiyunting.shiwuzhaoling.controller;

import meiyunting.shiwuzhaoling.model.Item;
import meiyunting.shiwuzhaoling.model.User;
import meiyunting.shiwuzhaoling.service.ItemService;
import meiyunting.shiwuzhaoling.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 物品API控制器，向其他微服务暴露失物招领平台的数据
 */
@RestController
@RequestMapping("/api/items")
public class ItemApiController {

    private final ItemService itemService;
    private final UserService userService;
    
    @Autowired
    public ItemApiController(ItemService itemService, UserService userService) {
        this.itemService = itemService;
        this.userService = userService;
    }
    
    /**
     * 获取用户发布的物品
     */
    @GetMapping("/user/{userId}")
    public List<Map<String, Object>> getUserItems(@PathVariable Long userId) {
        try {
            User user = userService.findById(userId);
            List<Item> items = itemService.getItemsByUser(user);
            return items.stream()
                    .map(this::convertToMap)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    /**
     * 获取单个物品信息
     */
    @GetMapping("/{id}")
    public Map<String, Object> getItem(@PathVariable Long id) {
        try {
            Item item = itemService.findItemById(id);
            return convertToMap(item);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "物品不存在");
            return error;
        }
    }
    
    /**
     * 获取最新物品列表
     */
    @GetMapping("/latest")
    public List<Map<String, Object>> getLatestItems() {
        List<Item> items = itemService.getAllItems();
        return items.stream()
                .limit(10)  // 只返回最新的10条
                .map(this::convertToMap)
                .collect(Collectors.toList());
    }
    
    /**
     * 将物品实体转换为Map
     */
    private Map<String, Object> convertToMap(Item item) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", item.getId());
        map.put("title", item.getTitle());
        map.put("description", item.getDescription());
        map.put("status", item.getStatus().name());
        map.put("type", item.getType().name());
        map.put("contactInfo", item.getContactInfo());
        map.put("imagePath", item.getImagePath());
        map.put("createdAt", item.getCreatedAt());
        map.put("lostTime", item.getLostTime());
        
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("id", item.getUser().getId());
        userMap.put("username", item.getUser().getUsername());
        map.put("user", userMap);
        
        if (item.getClaimedBy() != null) {
            Map<String, Object> claimedByMap = new HashMap<>();
            claimedByMap.put("id", item.getClaimedBy().getId());
            claimedByMap.put("username", item.getClaimedBy().getUsername());
            map.put("claimedBy", claimedByMap);
            map.put("claimedAt", item.getClaimedAt());
        }
        
        return map;
    }
} 